package com.example.demo.interceptor;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.pojo.TokenData;
import com.example.demo.pojo.User;
import com.example.demo.service.LendService;
import com.example.demo.service.impl.LendServiceImpl;
import com.example.demo.utils.CheckResult;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.ResultFactory;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 */
public class SecurityInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(SecurityInterceptor.class);

    //private LendService lendService = new LendServiceImpl();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //做判断， 解决预约是否超时问题
        //lendService.reservationTimeIsTimeOut();

        HttpSession session = request.getSession();
        //logger.info("token： " + request.getHeader("token"));
        String header = request.getHeader("token");
       // logger.info("header:"+header);
        if(header == null) {
            returnJson(response, JSON.toJSONString(ResultFactory.failureWithStatus(401, "您还没登录或登录过期，请先登录")));
            return false;
        }
        CheckResult checkResult = JwtUtil.validateJWT(header);
        if(checkResult.isSuccess()){
            //解析成功
            Claims claims = checkResult.getClaims();
            String subject = claims.getSubject();
            JSONObject jsonObject = JSONObject.parseObject(subject);
            TokenData tokenData = JSON.toJavaObject(jsonObject, TokenData.class);
            logger.info("tokenData:"+tokenData);
            session.setAttribute("currentUser",tokenData);
            return true;

        }else{
            //解析失败
            returnJson(response, JSON.toJSONString(ResultFactory.failureWithStatus(401,"token解析失败")));
            return false;
        }



    }
    //返回JSON数据
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        }catch (IOException e){

        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }


}
